# yun-cha-coffee PyCharm
# productTag Y
# 2025/8/30 下午5:38
from fastapi import APIRouter, Depends, HTTPException, status
from tortoise.exceptions import DoesNotExist, IntegrityError

from app.models import ProductTag, CoffeeProductTag, MerchandiseProductTag,CoffeeProduct,MerchandiseProduct
from pydantic import BaseModel, validator, Field
# from app.schemas import TagCreate
from datetime import datetime

productTag_api = APIRouter(prefix="/tags", tags=["中国云咖标签接口"])

@productTag_api.get("/", summary="获取标签列表")
async def get_tags():
    """获取标签列表"""
    tags = await ProductTag.all()
    return {
        "code": 200,
        "message": "查询成功",
        "data": tags
    }

class ProductTagIn(BaseModel):
    name:str
    created_at: datetime

class ProductTagOut(BaseModel):
    id: int
    name:str
    created_at: datetime

    class Config:
        from_attributes = True


@productTag_api.post("/", summary="创建标签")
async def create_tag(productTag_data: ProductTagIn):
    """创建新标签"""
    existing_tag = await ProductTag.get_or_none(name=productTag_data.name)
    if existing_tag:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="标签名称已存在"
        )

    try:
        tag = await ProductTag.create(**productTag_data.dict())
        return {
        "code": 200,
        "message": "创建标签成功",
        "data": tag
    }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建标签失败: {str(e)}"
        )


# 删除标签（同时删除所有关联）
@productTag_api.delete("/{tag_id}",summary="删除标签（同时删除所有关联）")
async def delete_tag(tag_id: int):
    """删除标签"""
    tag = await ProductTag.get_or_none(id=tag_id)
    if not tag:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="标签不存在"
        )

    # 先删除所有关联关系
    await CoffeeProductTag.filter(tag_id=tag_id).delete()
    await MerchandiseProductTag.filter(tag_id=tag_id).delete()

    # 删除标签
    await tag.delete()

    return {
        "code": 200,
        "message": "标签删除成功"
    }


# 修改标签功能
@productTag_api.put("/{tag_id}", summary="修改标签信息")
async def update_tag(tag_id: int, tag_data: ProductTagIn):
    """修改标签信息"""
    # 检查标签是否存在
    tag = await ProductTag.get_or_none(id=tag_id)
    if not tag:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="标签不存在"
        )

    # 检查新名称是否与其他标签冲突（排除自己）
    if tag_data.name != tag.name:
        existing_tag = await ProductTag.get_or_none(name=tag_data.name)
        if existing_tag:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="标签名称已存在"
            )

    # 更新标签信息
    update_data = tag_data.dict(exclude_unset=True)
    await ProductTag.filter(id=tag_id).update(**update_data)

    # 获取更新后的标签
    updated_tag = await ProductTag.get(id=tag_id)

    return {
        "code": 200,
        "message": "标签修改成功",
        "data": updated_tag
    }



@productTag_api.post("/coffee/{product_id}/{tag_id}",summary="为咖啡产品添加标签")
async def add_coffee_product_tag(product_id: int, tag_id: int):
    """为咖啡产品添加标签"""
    try:
        product = await CoffeeProduct.get(id=product_id)
        tag = await ProductTag.get(id=tag_id)
    except DoesNotExist:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="产品或标签不存在"
        )

    # 检查是否已存在该标签
    existing_relation = await CoffeeProductTag.get_or_none(
        product_id=product_id,
        tag_id=tag_id
    )
    if existing_relation:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="该产品已添加此标签"
        )

    try:
        # 创建关联关系
        await CoffeeProductTag.create(product_id=product_id, tag_id=tag_id)
        return {
            "code": 200,
            "message": "标签添加成功",
            # "data": {
            #     "product_id": product_id,
            #     "tag_id": tag_id,
            #     "product_name": product.name,
            #     "tag_name": tag.name
            # }
        }
    except IntegrityError:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="添加标签失败"
        )
@productTag_api.post("/merchandise/{product_id}/{tag_id}",summary="为周边商品添加标签")
async def add_merchandise_product_tag(product_id: int, tag_id: int):
    """为周边商品添加标签"""
    try:
        product = await MerchandiseProduct.get(id=product_id)
        tag = await ProductTag.get(id=tag_id)
    except DoesNotExist:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="产品或标签不存在"
        )

        # 检查是否已存在该标签
    existing_relation = await MerchandiseProductTag.get_or_none(
        product_id=product_id,
        tag_id=tag_id
    )
    if existing_relation:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="该产品已添加此标签"
        )

    try:
        # 创建关联关系
        await MerchandiseProductTag.create(product_id=product_id, tag_id=tag_id)
        return {
            "code": 200,
            "message": "标签添加成功",
            "data": {
                "product_id": product_id,
                "tag_id": tag_id,
                "product_name": product.name,
                "tag_name": tag.name
            }
        }
    except IntegrityError:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="添加标签失败"
        )

@productTag_api.delete("/coffee/{product_id}/{tag_id}",summary="移除咖啡产品标签")
async def remove_coffee_product_tag(product_id: int, tag_id: int):
    """移除咖啡产品标签"""
    # 检查关联关系是否存在
    relation = await CoffeeProductTag.get_or_none(
        product_id=product_id,
        tag_id=tag_id
    )
    if not relation:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="该产品未添加此标签"
        )

    await relation.delete()

    return {
        "code": 200,
        "message": "标签移除成功",
        "data": {
            "product_id": product_id,
            "tag_id": tag_id
        }
    }


# 获取产品的所有标签
@productTag_api.get("/coffee/{product_id}",summary="获取咖啡产品的所有标签")
async def get_coffee_product_tags(product_id: int):
    """获取咖啡产品的所有标签"""
    try:
        product = await CoffeeProduct.get(id=product_id)
    except DoesNotExist:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="产品不存在"
        )

    # 通过关联表查询标签
    tag_relations = await CoffeeProductTag.filter(product_id=product_id).prefetch_related('tag')
    tags = [relation.tag for relation in tag_relations]

    return {
        "code": 200,
        "message": "查询成功",
        "data": {
            "product_id": product_id,
            "product_name": product.name,
            "tags": tags
        }
    }

@productTag_api.delete("/merchandise/{product_id}/{tag_id}",summary="移除周边商品标签")
async def remove_merchandise_product_tag(product_id: int, tag_id: int):
    """移除周边商品标签"""
    # 检查关联关系是否存在
    relation = await MerchandiseProductTag.get_or_none(
        product_id=product_id,
        tag_id=tag_id
    )
    if not relation:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="该产品未添加此标签"
        )

    await relation.delete()

    return {
        "code": 200,
        "message": "标签移除成功",
        "data": {
            "product_id": product_id,
            "tag_id": tag_id
        }
    }

@productTag_api.get("/merchandise/{product_id}", summary="获取周边商品的所有标签")
async def get_merchandise_product_tags(product_id: int):
    """获取周边商品的所有标签"""
    try:
        product = await MerchandiseProduct.get(id=product_id)
    except DoesNotExist:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="周边商品不存在"
        )

    # 通过关联表查询标签
    tag_relations = await MerchandiseProductTag.filter(product_id=product_id).prefetch_related('tag')
    tags = [relation.tag for relation in tag_relations]

    return {
        "code": 200,
        "message": "查询成功",
        "data": {
            "product_id": product_id,
            "product_name": product.name,
            "tags": tags
        }
    }

